#! /usr/bin/env python
#coding=utf-8


import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))

import stat
import time
import mimetypes
import urllib.parse

if sys.version_info > (3, 0):
	from http.server import BaseHTTPRequestHandler
else:
	from BaseHTTPServer import BaseHTTPRequestHandler

from .products import Products
import config
import traceback

class RequestMatcher(object):
	def doGetRequest(self, handler, path_parts, xargs):
		pass

	def match(self, handler, path_parts):
		return None

class StaticFiles(RequestMatcher):
	def match(self, handler, path_parts):
		return self

	def doGetRequest(self, handler, path_parts, xargs):
		if len(path_parts) < 1 or path_parts[0] == "":
			file = "index.html"
		else:
			file = "/".join(path_parts)
		handler.sendNormalFile(os.path.join(config.HTML_PATH, file), False)

class OhosArchInfoRequestHandler(BaseHTTPRequestHandler):
	REQUEST_MATCHING_MODULES = (Products(), StaticFiles())

	@staticmethod
	def _parse_uri(uri):
		path = uri
		args = ""
		pos = uri.find('?')
		if pos >= 0:
			path = uri[:pos]
			args = uri[pos+1:]
		if path[0] == "/":
			path = path[1:]
		path_parts = [urllib.parse.unquote(k) for k in path.split("/")]

		xargs = {}
		if len(args) > 1:
			for arg in args.split('&'):
				if '' == arg:
					continue
				nvPair = arg.split('=')
				if len(nvPair) >= 2:
					xargs[nvPair[0]] = urllib.parse.unquote(nvPair[1])

		print("request path: %s, args:[%s]" % (str(path_parts), str(xargs)))
		return path_parts, xargs

	def _match_request(self, path_parts):
		for matcher in OhosArchInfoRequestHandler.REQUEST_MATCHING_MODULES:
			obj = matcher.match(self, path_parts)
			if obj:
				return obj
		return None

	def do_GET(self):
		(path_parts, xargs) = OhosArchInfoRequestHandler._parse_uri(self.path)
		rest = self._match_request(path_parts)
		if not rest:
			self.resFileNotFound()
			return

		xargs["_handler"] = self
		rest.doGetRequest(self, path_parts, xargs)
		print("GET " + self.path + " finished.")

	def resStrContent(self, resStr, xargs=None):
		# send back appropriate HTTP code
		self.send_response(200)
		if xargs and "format" in xargs and xargs["format"] == "svg":
			self.send_header("Content-type", 'image/svg+xml')
		elif xargs and "format" in xargs and xargs["format"] == "xml":
			self.send_header("Content-type", 'text/xml')
			path = self.path
			pos = self.path.find("?")
			if pos >= 0:
				path = self.path[:pos]
			self.send_header("Content-Disposition", 'attachment; filename="%s.xml"' % os.path.basename(path))
		else:
			self.send_header("Content-type", 'text/plain')

		try:
			buf = bytes(resStr, 'utf-8')
		except:
			buf = resStr
		self.send_header("Content-Length", len(buf))
		self.end_headers()

		try:
			self.wfile.write(bytes(resStr, 'utf-8'))
		except:
			try:
				self.wfile.write(resStr)
			except:
				traceback.print_exc()

	def resFileNotFound(self):
		# send back appropriate HTTP code
		self.send_response(404)
		# describe the server software in use!
		self.send_header("Server", "HandyWeb")
		self.send_header("Connection", "Close")
		# close off headers
		self.end_headers()

	def sendNormalFile(self, name, cache = False):
		print("Local file name is: " + name)
		# Open the file first
		try:
			resFile = open(name, 'rb')
		except:
			self.resFileNotFound()
			return

		statInfo = os.stat(name)
		#If-Modified-Since: Wed, 16 Jul 2008 07:05:50 GMT
		#if self.headers.has_key('If-Modified-Since'):
		#	try:
		#		#print self.headers['If-Modified-Since']
		#		tmpStr = self.headers['If-Modified-Since'].split(',')[1]
		#		tmpStr = string.strip(tmpStr)
		#		tmpStr = tmpStr[:tmpStr.find(' GMT')]
		#		#print tmpStr
		#		reqTime = time.mktime(time.strptime(tmpStr, "%d %b %Y %H:%M:%S"))
		#		if statInfo[stat.ST_MTIME] <= reqTime:
		#			self.resFileNotModified()
		#			return
		#	except:
		#		pass

		# send back appropriate HTTP code
		self.send_response(200)

		# tell them we're sending HTML
		suffix = os.path.basename(name)
		suffix = suffix[suffix.rfind('.'):]
		self.send_header('Last-Modified', time.ctime(statInfo[stat.ST_MTIME]))
		try:
			self.send_header("Content-type", mimetypes.types_map[suffix])
		except:
			self.send_header("Content-type", 'text/plain')
		# describe the server software in use!
		#self.send_header("Server", "HandyWeb")
		#suffix = '%d' % os.stat(name)[stat.ST_SIZE]

		self.send_header("Content-Length", str(os.stat(name)[stat.ST_SIZE]))

		# close off headers
		self.end_headers()

		# Send the response
		data = resFile.read()
		resFile.close()
		try:
			self.wfile.write(data)
		except:
			traceback.print_exc()
